﻿using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using thousandclear.Data;
using thousandClear.Areas.Admin.Models;
using thousandClear.Util.Media;
using thousandClear.Util.Setting;

namespace thousandClear.Areas.Admin.Controllers
{
    public class ShopItemController : Controller
    {
        private qianjingEntities _db;
        // GET: Admin/ShopItem
        public ActionResult Index(string pg, int? n)
        {
            int page = 1;
            if (!string.IsNullOrEmpty(pg))
            {
                page = int.Parse(pg);
            }
            Session["page"] = page;
            int count = 10;
            int totalCount = 0;
            int totalPage = 1;
            int currentPage = page;
            int pageCount = count;

            List<D_ShopGood> records = null;
            List<GoodViewModel> list = new List<GoodViewModel>();

            using (_db = new qianjingEntities())
            {
                var query = _db.D_ShopGood;

                totalCount = query.Count();

                if (n == null || n == 0)
                {
                    records = query.OrderByDescending(a => a.DSGID).Where(a => a.State == 1).Skip((page - 1) * count).Take(count).ToList();
                }
                else
                {
                    records = query.OrderByDescending(a => a.DSGID).Where(a => a.State == 1 & a.squm == n).Skip((page - 1) * count).Take(count).ToList();
                }



            }

            foreach (var item in records)
            {
                list.Add(new GoodViewModel
                {
                    Id = item.DSGID,
                    Name = item.Name,
                    Desc = item.ppDesc,
                    SalePrice = (item.SalePrice == null ? 0 : item.SalePrice.Value / 100).ToString("#0.00"),
                    MarketPrice = (item.MarketPrice == null ? 0 : item.MarketPrice.Value).ToString(),
                    Inventory = item.Invertory == null ? 0 : item.Invertory.Value,
                    OnSold = item.OnSaled == null ? 0 : item.OnSaled.Value,
                    Putaway = item.Putaway == null ? 0 : item.Putaway.Value,
                    Weight = (item.Weight == null ? 0 : item.Weight.Value / 1000).ToString("#0.000"),
                    Scroll = item.ppScroll == null ? 0 : item.ppScroll.Value,
                    Mode = item.Mode == null ? 0 : item.Mode.Value,
                    EditUrl = string.Format("../../../admin/ShopItem/Edit/{0}", item.DSGID),
                    SeqNum = item.SeqNum ?? 0,
                    Credit = (item.Credit==null?0:item.Credit.Value).ToString(),
             
                    //level2Name = item.level2ID.Value.ToString(),
                    squm = item.squm == null ? 0 : item.squm.Value,

                });
            }

            ViewBag.TotalCount = totalCount;
            totalPage = int.Parse((totalCount / count).ToString()) + (totalCount % count == 0 ? 0 : 1);
            ViewBag.TotalPage = totalPage;
            ViewBag.CurrentPage = currentPage;
            ViewBag.PageCount = pageCount;

            if (page <= 1)
            {
                ViewBag.PrevPageUrl = string.Format("http://www.qianjing-china.com/thousandClear/admin/ShopItem?pg={0}&count={1}", page, count);
            }
            else
            {
                ViewBag.PrevPageUrl = string.Format("http://www.qianjing-china.com/thousandClear/admin/ShopItem?pg={0}&count={1}", page - 1, count);
            }

            if (page >= totalPage)
            {
                ViewBag.NextPageUrl = string.Format("http://www.qianjing-china.com/thousandClear/admin/ShopItem?pg={0}&count={1}", page, count);
            }
            else
            {
                ViewBag.NextPageUrl = string.Format("http://www.qianjing-china.com/thousandClear/admin/ShopItem?pg={0}&count={1}", page + 1, count);
            }


            return View(list);
        }

        // POST: Admin/Add
        [HttpPost]
        public ActionResult Add(string data)
        {

            AppSetting setting = new AppSetting();
            ImageResolver resolver = new ImageResolver();


            var post = JObject.Parse(data);
            //int squm = post["squm"].Value<int>();
            string goodName = post["goodName"].Value<string>();
            string goodDesc = post["goodDesc"].Value<string>();
            int salePrice = post["salePrice"].Value<int>();
            //int marketPrice = post["marketPrice"].Value<int>();
            //int inventory = post["inventory"].Value<int>();
            //int weight = post["weight"].Value<int>();
            int putaway = post["putaway"].Value<int>();
            int mode = post["mode"].Value<int>();
            string imgUrl = post["imgUrl"].Value<string>();
            //string imgUrl2 = post["imgUrl2"].Value<string>();
            //string imgUrl3 = post["imgUrl3"].Value<string>();
            string thumbUrl = post["thumbUrl"].Value<string>();
            //int scroll = post["scroll"].Value<int>();
            int seqnum = post["seqnum"].Value<int>();
            //int level2id = post["level2ID"].Value<int>();
            //string quality = post["quality"].Value<string>();
            //string size = post["size"].Value<string>();
           
            //获取积分
            decimal credit = post["credit"].Value<decimal>();


            string filePath = setting.AppUploadFolder + "\\Good\\Image";
            string imgFileName = string.Empty;
            //string imgFileName2 = string.Empty;
            //string imgFileName3 = string.Empty;
            string thumbFileName = string.Empty;

            if (!string.IsNullOrEmpty(imgUrl))
            {
                imgFileName = Guid.NewGuid().ToString() + "." + resolver.GetExt(imgUrl);
                resolver.SaveBase64(imgUrl, filePath, imgFileName);
            }
            //if (!string.IsNullOrEmpty(imgUrl2))
            //{
            //    imgFileName2 = Guid.NewGuid().ToString() + "." + resolver.GetExt(imgUrl2);
            //    resolver.SaveBase64(imgUrl2, filePath, imgFileName2);
            //}
            //if (!string.IsNullOrEmpty(imgUrl3))
            //{
            //    imgFileName3 = Guid.NewGuid().ToString() + "." + resolver.GetExt(imgUrl3);
            //    resolver.SaveBase64(imgUrl3, filePath, imgFileName3);
            //}

            if (!string.IsNullOrEmpty(thumbUrl))
            {
                thumbFileName = Guid.NewGuid().ToString() + "." + resolver.GetExt(thumbUrl);
                resolver.SaveBase64(thumbUrl, filePath, thumbFileName);
            }

            using (_db = new qianjingEntities())
            {
                
                _db.D_ShopGood.Add(new D_ShopGood
                {
                    Name = goodName,
                    //ppDesc = goodDesc,
                    SalePrice = salePrice,
                    //MarketPrice = marketPrice,
                    //Inventory = inventory,
                    Putaway = putaway,
                    CreatedTime = DateTime.Now,
                    UpdatedTime = DateTime.Now,
                    //Version = DateTime.Now.Ticks,
                    ImgUrl = imgFileName,
                    ImgDesc = goodDesc.Replace("\r", ""),
                    //ImgUrl2 = imgFileName2,
                    //ImgUrl3 = imgFileName3,
                    ThumbUrl = thumbFileName,
                    //Weight = weight,
                    //Scroll = scroll,
                    SeqNum = seqnum,
                    //level2ID = level2id,
                    State = 1,
                    //Size = size,
                    //quality = quality,
                    //squm = squm,
                    OnHold = 0,
                    OnSaled = 0,
                    Credit = credit,
                    Mode = mode
                    //Limited = numlimt

                });

                _db.SaveChanges();
            }

            return RedirectToAction("Index", new { page = 1, count = 10 });
        }
        public ActionResult Add()
        {
            return View();
        }

        [HttpPost]
        public void RemoveGood(string goodid)
        {
            using (var db = new qianjingEntities())
            {
                var query = db.D_ShopGood.FirstOrDefault(od => od.DSGID.ToString().Trim() == goodid.ToString().Trim());

                query.State = 0;

                db.SaveChanges();
            }
        }

        // GET: Admin/Edit/{id}
        public ActionResult Edit(long id)
        {

            GoodEditModel model = new GoodEditModel();

            AppSetting setting = new AppSetting();

            using (_db = new qianjingEntities())
            {
                var record = _db.D_ShopGood.FirstOrDefault(a => a.DSGID == id);

                if (record != null)
                {
                    model.Id = record.DSGID;
                    model.Name = record.Name;
                    model.squm = record.squm == null ? 0 : record.squm.Value;

                    model.Desc = string.IsNullOrEmpty(record.ImgDesc) ? "" : record.ImgDesc.Replace("\n", "<br/>");

                    //model.ImgDesc = record.ImgDesc;
                    model.SalePrice = record.SalePrice == null ? 0 : (int)record.SalePrice.Value;
                    model.MarketPrice = record.MarketPrice == null ? 0 : (int)record.MarketPrice.Value;
                    model.Inventory = record.Invertory == null ? 0 : record.Invertory.Value;
                    model.Putaway = record.Putaway == null ? 0 : record.Putaway.Value;
                    //model.Weight = record.Weight == null ? 0 : record.Weight.Value;
                    model.ImgUrl = record.ImgUrl;
                    //model.ImgUrl2 = record.ImgUrl2;
                    //model.ImgUrl3 = record.ImgUrl3;
                    model.ThumbUrl = record.ThumbUrl;
                    model.Scroll = record.ppScroll == null ? 0 : record.ppScroll.Value;
                    model.Mode = record.Mode == null ? 0 : record.Mode.Value;
                    model.UploadUrl = string.Format("{0}/{1}", setting.AppDomainName, "/statics/upload/good/image");
                    model.SeqNum = record.SeqNum ?? 0;
                    model.Credit = record.Credit == null ? 0 : (int)record.Credit.Value;
                    //model.level2ID = (int)record.level2ID;
                    //model.size = record.Size;
                    //model.quality = record.quality;

                    //model.isLinited = record.isLimited == null ? 0 : record.isLimited.Value;
                    //model.limitedNum = record.Limited == null ? 0 : record.Limited.Value;

                }
            }
            //List<good_type_level2> records = null;
            //List<GoodAddModel> list = new List<GoodAddModel>();
            //using (_db = new TeaArtDbContext())
            //{
            //    var query = from m in _db.good_type_level2
            //                where m.Status == 1
            //                select m;
            //    records = query.ToList();
            //}
            //foreach (var item in records)
            //{
            //    list.Add(new GoodAddModel
            //    {
            //        Id = item.id,
            //        TypeName = item.TypeName
            //    });
            //}
            //ViewBag.List1 = list;

            return View(model);
        }

        [HttpPost]
        public ActionResult Edit(string data)
        {
            AppSetting setting = new AppSetting();
            ImageResolver resolver = new ImageResolver();

            var post = JObject.Parse(data);
            long id = post["id"].Value<long>();
            //int squm = post["squm"].Value<int>();
            string goodName = post["goodName"].Value<string>();
            string goodDesc = post["goodDesc"].Value<string>();
            int salePrice = post["salePrice"].Value<int>();
            //int marketPrice = post["marketPrice"].Value<int>();
            //int inventory = post["inventory"].Value<int>();
            //int weight = post["weight"].Value<int>();
            int putaway = post["putaway"].Value<int>();
            int mode = post["mode"].Value<int>();
            string imgUrl = post["imgUrl"].Value<string>();
            //string imgUrl2 = post["imgUrl2"].Value<string>();
            //string imgUrl3 = post["imgUrl3"].Value<string>();
            string thumbUrl = post["thumbUrl"].Value<string>();
            //int scroll = post["scroll"].Value<int>();
            int seqnum = post["seqnum"].Value<int>();
            //int level2id = post["level2ID"].Value<int>();
            //string quality = post["quality"].Value<string>();
            //string size = post["size"].Value<string>();

            //获取积分
            int credit = post["credit"].Value<int>();

            string filePath = setting.AppUploadFolder + "\\Good\\Image";
            string imgFileName = string.Empty;
            //string imgFileName2 = string.Empty;
            //string imgFileName3 = string.Empty;
            string thumbFileName = string.Empty;

            using (_db = new qianjingEntities())
            {
                var record = _db.D_ShopGood.FirstOrDefault(a => a.DSGID == id);

                if (record != null)
                {
                    if (!string.IsNullOrEmpty(imgUrl) && record.ImgUrl != imgUrl)
                    {
                        imgFileName = Guid.NewGuid().ToString() + "." + resolver.GetExt(imgUrl);
                        resolver.SaveBase64(imgUrl, filePath, imgFileName);

                        record.ImgUrl = imgFileName;
                    }
                    //if (!string.IsNullOrEmpty(imgUrl2) && record.ImgUrl2 != imgUrl2)
                    //{
                    //    imgFileName2 = Guid.NewGuid().ToString() + "." + resolver.GetExt(imgUrl2);
                    //    resolver.SaveBase64(imgUrl2, filePath, imgFileName2);

                    //    record.ImgUrl2 = imgFileName2;
                    //}
                    //if (!string.IsNullOrEmpty(imgUrl3) && record.ImgUrl3 != imgUrl3)
                    //{
                    //    imgFileName3 = Guid.NewGuid().ToString() + "." + resolver.GetExt(imgUrl3);
                    //    resolver.SaveBase64(imgUrl3, filePath, imgFileName3);

                    //    record.ImgUrl3 = imgFileName3;
                    //}

                    if (!string.IsNullOrEmpty(thumbUrl) && record.ThumbUrl != thumbUrl)
                    {
                        thumbFileName = Guid.NewGuid().ToString() + "." + resolver.GetExt(thumbUrl);
                        resolver.SaveBase64(thumbUrl, filePath, thumbFileName);

                        record.ThumbUrl = thumbFileName;
                    }

                    record.Name = goodName;
                    //record.Desc = goodDesc;
                    record.ImgDesc = goodDesc.Replace("\r", "");
                    record.SalePrice = salePrice;
                    //record.MarketPrice = marketPrice;
                    //record.Inventory = inventory;
                    record.Putaway = putaway;
                    record.UpdatedTime = DateTime.Now;
                    //record.Version = DateTime.Now.Ticks;
                    //record.Weight = weight;
                    //record.Scroll = scroll;
                    record.Mode = mode;
                    record.SeqNum = seqnum;
                    //record.Size = size;
                    //record.quality = quality;
                    //record.squm = seqnum;
                }

                _db.SaveChanges();
            }
            int _page = (int)Session["page"];
            return RedirectToAction("Index", new { pg = _page, count = 10 });
        }
    }
}